package com.example.oppo

import android.os.Environment
import android.renderscript.RenderScript
import java.io.File
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

//单例
class ZkPreLoadManager private constructor() {

    companion object {
        const val TAG = "ZkPreLoadManager.class}"
        const val initialCapacity = 10;
        const val corePoolSize = 1;
        const val maxPoolSeze = 1;
        const val keepAliveTime = 0L;

        val instance: ZkPreLoadManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ZkPreLoadManager()
        }
    }

    init {
        val zipFileDir = File(Environment.getDownloadCacheDirectory(),"zkVideoZipCache")
        val unZipFileDir = File(Environment.getDownloadCacheDirectory(),"zkVideoUnZipCache")
        if(!zipFileDir.exists()) {
            zipFileDir.mkdirs()
        }
        if(!unZipFileDir.exists()){
            unZipFileDir.mkdirs()
        }
    }

    //lateinit 只用于变量 var，而 lazy 只用于常量 val
    private val taskList: MutableMap<String, TaskInfo> by lazy {
        mutableMapOf()
    }

    private val priorityBlockingQueue: PriorityBlockingQueue<Runnable> =
        object : PriorityBlockingQueue<Runnable>(
            initialCapacity
        ) {
            override fun offer(o: Runnable): Boolean {
                return if (super.size < initialCapacity) super.offer(o) else false
            }
        }

    val threadPoolExcutor: ThreadPoolExecutor = ThreadPoolExecutor(
        corePoolSize,
        maxPoolSeze,
        keepAliveTime,
        TimeUnit.MILLISECONDS,
        priorityBlockingQueue,
        ZkThreadFactory(),
        ThreadPoolExecutor.DiscardOldestPolicy()
    )



    class ZkThreadFactory : ThreadFactory {
        override fun newThread(r: Runnable?): Thread {
            var thread = Thread(r, "zkVideoCacheThread")
            thread.priority = Thread.NORM_PRIORITY
            return thread
        }
    }




    fun resumeZkTask(zkTask: ZkTask) {
        threadPoolExcutor.execute(zkTask)
    }


}